<!-- 客户管理-新增客户 -->
<template>
  <div class="client-add">
    <pageHeader
      v-if="type === 'add'"
      :title="title"
      :breadCrumb="breadCrumb"
      :show-back="true"
    >
      <template #footer>
        <a-space v-if="type === 'add' && !id">
          <a-button type="primary" @click="save">保存</a-button>
          <a-button @click="cancel">取消</a-button></a-space
        >
      </template>
      <div class="base-info">
        <!-- <a-button
          :style="{
            float: 'right',
          }"
          type="primary"
          size="large"
          v-if="type !== 'add'"
          @click="isEditBtn"
          >编辑</a-button
        > -->
        <TitleBox title="基本信息" />
        <UploadFile
          ref="FileRef"
          v-model:file-list="headFile"
          listType="picture-card"
          class="avatar"
          :limit="1"
          :isShowRemove="type === 'add' || type === 'edit'"
        ></UploadFile>
        <div class="base-info-header">
          <a-form
            :model="form.list"
            ref="formNameRef"
            :rules="rules"
            layout="vertical"
          >
            <a-form-item field="name" label="客户名称：">
              <a-input
                placeholder="请输入客户名称"
                :style="{
                  width: '100%',
                }"
                :disabled="type !== 'add' && !isEdit"
                v-model="form.list.name"
                size="large"
              />
            </a-form-item>
          </a-form>
          <a-form
            :model="form.list"
            ref="formInfoRef"
            :rules="rules"
            auto-label-width
          >
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="customerNumber" label="客户编号：">
                  <a-input
                    placeholder="系统自动生成"
                    size="large"
                    v-model="form.list.customerNumber"
                    disabled
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="level" label="客户级别：">
                  <a-select
                    placeholder="请选择客户级别"
                    v-model="form.list.level"
                    :disabled="type !== 'add' && !isEdit"
                  >
                    <a-option
                      v-for="item in customerLevel"
                      :key="item.id"
                      :value="item.id"
                      >{{ item.name }}</a-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="customerContactPhone" label="联系电话：">
                  <a-input-number
                    :min="1"
                    placeholder="请输入联系电话"
                    size="large"
                    :disabled="type !== 'add' && !isEdit"
                    v-model="form.list.customerContactPhone"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="customerEmail" label="联系邮箱：">
                  <a-input
                    placeholder="请输入联系邮箱"
                    size="large"
                    :disabled="type !== 'add' && !isEdit"
                    v-model="form.list.customerEmail"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="city" label="省市区：">
                  <a-cascader
                    :options="pcCode"
                    :disabled="type !== 'add' && !isEdit"
                    v-model="form.list.city"
                    :field-names="fieldNames"
                    placeholder="请选择省市区"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="address" label="联系地址：">
                  <a-input
                    class="address"
                    placeholder="请输入联系地址"
                    size="large"
                    v-model="form.list.address"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="sourceId" label="客户来源：">
                  <a-select
                    placeholder="请选择客户来源"
                    v-model="form.list.sourceId"
                    :disabled="type !== 'add' && !isEdit"
                  >
                    <a-option
                      v-for="item in customerFrom"
                      :key="item.id"
                      :value="item.id"
                      >{{ item.name }}</a-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="industry" label="客户行业：">
                  <a-input
                    placeholder="请输入客户行业"
                    size="large"
                    v-model="form.list.industry"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="specialty" label="客户领域：">
                  <a-input
                    placeholder="请输入领域名称"
                    size="large"
                    v-model="form.list.specialty"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="salesId" label="销售负责人：">
                  <a-select
                    placeholder="请选择销售负责人："
                    v-model="form.list.salesId"
                    :disabled="type !== 'add' && !isEdit"
                    allow-search
                  >
                    <a-option
                      v-for="item in PersonnelInfoData"
                      :key="item.id"
                      :value="item.id"
                      >{{ item.name }}</a-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="customerType" label="客户类别：">
                  <a-select
                    placeholder="请选择客户类别："
                    v-model="form.list.customerType"
                    :disabled="type !== 'add' && !isEdit"
                  >
                    <a-option
                      v-for="item in customerType"
                      :key="item.id"
                      :value="item.id"
                      >{{ item.name }}</a-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="credit" label="信用额度：">
                  <div>
                    <a-switch :disabled="type !== 'add' && !isEdit" />
                    <icon-info-circle-fill
                      :style="{
                        color: '#5a9cf8',
                        marginLeft: '10px',
                        marginRight: '10px',
                      }"
                    />
                    <span
                      :style="{
                        position: 'absolute',
                        color: '#ccc',
                      }"
                    >
                      根据付款方式，允许客户订单的累计欠款信用额度，开启并达到欠款额度则不允许该客户下新订单，直到付清欠款
                    </span>
                  </div>
                  <div>
                    <a-space>
                      <a-input-number
                        :min="1"
                        :style="{
                          width: '320px',
                          top: '20px',
                          position: 'relative',
                        }"
                        placeholder="请输入借用额度"
                        v-model="form.list.credit"
                        :hide-button="true"
                        :disabled="type !== 'add' && !isEdit"
                      >
                        <template #prepend>￥</template>
                        <template #append>
                          <a-select
                            :disabled="type !== 'add' && !isEdit"
                            :style="{
                              width: '100px',
                            }"
                            placeholder="人民币"
                          >
                            <a-option>人民币</a-option>
                            <a-option>美金</a-option>
                          </a-select>
                        </template>
                      </a-input-number>
                      <a-select
                        :style="{
                          width: '160px',
                          top: '20px',
                          position: 'relative',
                        }"
                        v-model="form.list.creditUnit"
                        placeholder="请选择额度单位"
                        :trigger-props="{ autoFitPopupMinWidth: true }"
                      >
                        <a-option value="千">千</a-option>
                        <a-option value="万">万</a-option>
                        <a-option value="十万">十万</a-option>
                        <a-option value="百万">百万</a-option>
                      </a-select>
                    </a-space>
                  </div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- <div class="title-item">
          <a-space style="width: 100%; justify-content: space-between">
            <a-space style="margin-left: 40px">
              <div
                style="
                  width: 5px;
                  height: 23px;
                  background-color: rgba(61, 126, 255, 1);
                  border: none;
                  border-radius: 2px;
                "
              ></div>
              <div>联系人信息</div></a-space
            >

            </a-space
          >
        </div> -->
        <TitleBox title="联系人信息"
          ><template #buts
            ><a-link @click="addPerson" type="text"
              >添加联系人</a-link
            ></template
          ></TitleBox
        >
        <div class="base-info-extra">
          <a-form
            auto-label-width
            :model="form.list"
            :rules="rules"
            ref="formRef"
          >
            <!-- <h3 style="display: flex; justify-content: space-between"
              ><div>联系人信息</div>
             </h3
            > -->
            <div
              v-for="(item, index) in form.list.person"
              :key="index"
              class="contact-info"
              style="margin-top: 20px"
            >
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="联系人姓名：">
                    <a-input
                      placeholder="请输入联系人姓名"
                      size="large"
                      v-model="item.name"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="联系人电话：">
                    <a-input
                      placeholder="请输入联系人电话"
                      size="large"
                      v-model="item.phone"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="联系人职位：">
                    <a-input
                      placeholder="请输入联系人职位"
                      size="large"
                      v-model="item.job"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="联系人部门：">
                    <a-input
                      placeholder="请输入联系人部门"
                      size="large"
                      v-model="item.department"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="办公地点:">
                    <a-input
                      placeholder="请输入办公地点"
                      size="large"
                      v-model="item.address"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="决策作用：">
                    <a-input
                      placeholder="请输入决策作用"
                      size="large"
                      v-model="item.decision"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="是否为首要联系人:">
                    <a-switch
                      @change="setPersonPrimaryContact($event, index)"
                      v-model="item.primaryContact"
                      :checked-value="1"
                      :unchecked-value="0"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    field="contactDepartment"
                    label="是否为决策关键人:"
                  >
                    <a-switch
                      v-model="item.primaryDecision"
                      :checked-value="1"
                      :unchecked-value="0"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item
                    field="contactPosition"
                    style="
                      display: flex;
                      align-items: content;
                      justify-content: content;
                    "
                  >
                    <a-button
                      type="text"
                      status="danger"
                      @click="delPerson(index)"
                      >删除联系人</a-button
                    >
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </a-form>
        </div>

        <TitleBox title="收货人信息"
          ><template #buts
            ><a-link @click="addEntry" type="text">添加收货人</a-link></template
          ></TitleBox
        >
        <div class="base-info-extra">
          <div
            v-for="(item, index) in form.list.entry"
            :key="index"
            class="contact-info"
            style="margin-top: 20px"
          >
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="收货人姓名：">
                  <a-input
                    placeholder="请输入收货人姓名"
                    size="large"
                    v-model="item.name"
                    :disabled="type !== 'add'"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="收货人电话：">
                  <a-input
                    placeholder="请输入收货人电话"
                    size="large"
                    v-model="item.phone"
                    :disabled="type !== 'add'"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="收货人地址：">
                  <a-input
                    placeholder="请输入收货人地址"
                    size="large"
                    v-model="item.address"
                    :disabled="type !== 'add'"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="是否为首要收货人:">
                  <a-switch
                    @change="setPrimaryContact($event, index)"
                    v-model="item.primaryContact"
                    :checked-value="1"
                    :unchecked-value="0"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="contactPosition" label="备注：">
                  <a-textarea
                    placeholder="请输入备注"
                    size="large"
                    v-model="item.remark"
                    :disabled="type !== 'add'"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  field="contactPosition"
                  style="
                    display: flex;
                    align-items: content;
                    justify-content: content;
                  "
                >
                  <a-button type="text" status="danger" @click="delEntry(index)"
                    >删除收货人</a-button
                  >
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>

        <TitleBox title="发票信息" />
        <div class="base-info-extra"
          ><div class="invoice-info">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="companyTitle" label="公司抬头：">
                  <a-input
                    placeholder="请输入公司抬头"
                    size="large"
                    v-model="form.list.companyTitle"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="ein" label="税号：">
                  <a-input-number
                    :min="1"
                    placeholder="请输入税号"
                    size="large"
                    v-model="form.list.ein"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="companyPhone" label="联系电话：">
                  <a-input-number
                    :min="1"
                    placeholder="请输入联系电话"
                    size="large"
                    v-model="form.list.companyPhone"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="companyAddress" label="联系地址：">
                  <a-input
                    placeholder="请输入联系地址"
                    size="large"
                    v-model="form.list.companyAddress"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>

        <TitleBox title="客户账号信息" />
        <div class="base-info-extra">
          <div class="client-info">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="accountName" label="账户名称：">
                  <a-input
                    placeholder="请输入账户名称"
                    size="large"
                    v-model="form.list.accountName"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="accountNumber" label="银行账号：">
                  <a-input-number
                    :min="1"
                    placeholder="请输入银行账号"
                    size="large"
                    v-model="form.list.accountNumber"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="accountCity" label="开户省市：">
                  <a-input
                    placeholder="请输入开户省市"
                    size="large"
                    v-model="form.list.accountCity"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="accountBank" label="开户银行：">
                  <a-input
                    placeholder="请输入开户银行"
                    size="large"
                    v-model="form.list.accountBank"
                    :disabled="type !== 'add' && !isEdit"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>

        <TitleBox title="备注信息"></TitleBox>
        <div class="base-info-extra">
          <div class="remarks-info">
            <a-row :gutter="16">
              <a-col :span="24">
                <a-textarea
                  placeholder=""
                  show-word-limit
                  :max-length="300"
                  allow-clear
                  :auto-size="{
                    minRows: 5,
                  }"
                  v-model="form.list.remark"
                  :disabled="type !== 'add' && !isEdit"
                />
              </a-col>
            </a-row>
          </div>
        </div>

        <Enterprise ref="enterpriseRef" :form="enterpriseForm"></Enterprise>
      </div>
      <div
        v-if="type !== 'add' || route.query.id"
        style="
          display: flex;
          flex-direction: row-reverse;
          margin-right: 60px;
          margin-top: 20;
        "
      >
        <a-button type="primary" @click="save">保存</a-button>
        <a-button
          :style="{
            margin: '0px 20px',
          }"
          @click="cancel"
          >取消</a-button
        >
      </div>
    </pageHeader>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import {
    PostClientAdd,
    GetClientDetailTabs,
    putClientDetail,
  } from '@/api/order-management/client-management/client-list/index';
  import regex from '@/utils/regex';
  import pcCode from '@/assets/json/pca-code.json';
  import { GetClientSettingInfo } from '@/api/order-management/client-management/base-setting/index';
  import { GetPersonnelinformation } from '@/api/home/System settings/personal-information/index';
  import { IClientAddInfo, IEnterprise } from '@/types/order';
  import { FileUpload } from '@/utils/upload';
  import { getToken } from '@/utils/auth';
  import { openChoiceFile } from '@/utils/file';
  import { Message } from '@arco-design/web-vue';

  const rIndex = ref(-1);
  const router = useRouter();
  const route = useRoute();
  const type = computed(() => route.query.type); // 判断是新增客户还是看客户的基本信息
  const id = Number(route.query.id); // 储存客户id
  const title: string = '新增客户';
  let headPortraitFormData = reactive<{ file?: File }>({});
  const breadCrumb: string[] = ['订单管理', '客户管理', '客户列表', '新增客户'];
  let file = ref(); // 储存头像
  const isHead = ref();
  const formNameRef = ref();
  const formInfoRef = ref();
  const formRef = ref();
  const form = reactive<any>({
    list: {
      id: undefined,
      name: '', // 客户名称
      headPortrait: '', // 头像
      customerNumber: '', // 客户联系编号
      level: undefined, // 客户级别
      customerContactPhone: undefined, // 客户联系电话
      customerEmail: '', // 客户联系邮箱
      city: '', // 省市区
      address: '', // 客户联系地址
      sourceId: undefined, // 客户来源
      industry: '', // 客户行业
      specialty: '', // 客户专业：
      registrationId: undefined, // 建档人id,
      salesId: undefined, // 销售负责人id
      customerType: undefined, //客户类别
      credit: undefined, // 信贷
      contactName: '', // 联系人姓名
      contactPhone: undefined, // 联系人电话
      contactPosition: '', // 联系人职位
      contactDepartment: '', // 联系人部门
      companyTitle: '', // 公司抬头
      ein: undefined, // 税号
      companyPhone: undefined, // 公司电话
      companyAddress: '', // 公司地址
      companyNumber: undefined, // 公司银行账号
      companyBank: '', // 公司开户银行,
      accountName: '', // 账号名称
      accountNumber: undefined, // 银行账号
      accountCity: '', // 开户省市
      accountBank: '', // 开户银行
      remark: '', // 备注
      isNeedPerfect: null,
      creditUnit: '',
      file: [],
      entry: [
        { name: '', phone: '', address: '', primaryContact: 1, remark: '' },
      ],
      person: [
        {
          name: '',
          phone: '',
          address: '',
          primaryContact: 1,
          primaryDecision: 1,
          job: '',
          department: '',
          decision: '',
        },
      ],
    },
  });
  const visible1 = ref(false);
  const enterpriseForm = reactive<IEnterprise>({
    businessLicense: '', // 营业执照
    unifiedSocialCreditCodes: '', // 统一社会信用代码
    enterpriseName: '', // 企业名称
    legalRepresentative: '', // 法定代表人
    registrationStatus: '', // 登记状态
    establishmentDate: undefined, // 成立日期
    registeredCapital: '', // 注册资本
    paidCapital: '', // 实缴资本
    approvalDate: undefined, // 核准日期
    organizationCode: '', // 组织机构代码
    businessNo: undefined, // 工商注册号
    taxpayerNo: undefined, // 纳税人号
    enterpriseType: '', // 企业类型
    operationTerm: '', // 营业期限
    taxpayerQualification: '', // 纳税人资质
    industrySector: '', // 所属行业
    localArea: '', // 所属地区
    registrationAuthority: '', // 登记机关
    personnelSize: '', // 人员规模
    insuredPeople: undefined, // 参保人数
    formerName: '', // 曾用名
    englishName: '', // 英文名
    enterpriseCode: '', // 进出口企业代码
    registeredAddress: '', // 注册地址
    mainBusiness: '', // 主要经营
    file: [],
  });

  let enterpriseRef = ref(); // 储存enterprise的ref

  let headFile = computed({
    get() {
      const fileList = form.list.file.filter((i) => i.fileType === 1);
      return fileList.length
        ? [
            {
              fileUrl: fileList[0].fileAddr,
              fileName: fileList[0].name,
            },
          ]
        : [];
    },
    set(val) {
      if (val.length > 0) {
        form.list.file.push({
          addr: val[0].sourceAddr,
          name: val[0].fileName,
          fileAddr: val[0].fileUrl,
          fileType: 1,
        });
      } else {
        if (!form.list.file.length) return;
        const supplierFileIndex = form.list.file.findIndex(
          (file) => file.fileType === 1
        );
        form.list.file.splice(supplierFileIndex, 1);
      }
    },
  });

  // 校验手机
  const validatePhone = (val: any, callback: any) => {
    if (val === undefined) callback(new Error('请输入电话号码'));
    else if (!regex.phone.role.test(val)) callback('请输入正确的电话号码');
    return true;
  };

  // 校验邮箱
  const validateEmail = (val: any, callback: any) => {
    if (val === undefined) callback(new Error('请输入邮箱'));
    else if (!regex.email.role.test(val)) callback('请输入正确的邮箱');
    return true;
  };

  const addEntry = () => {
    form.list.entry.push({
      name: '',
      phone: '',
      address: '',
      primaryContact: 0,
      remark: '',
    });
  };

  const setPrimaryContact = (e: number, rowIndex: number) => {
    if (e === 1)
      form.list.entry.forEach((item: number, index: number) => {
        if (index !== rowIndex) item.primaryContact = 0;
      });
  };

  const delEntry = (rowIndex: number) => {
    if (form.list.entry.length === 1) return;
    form.list.entry.splice(rowIndex, 1);
  };

  const addPerson = () => {
    form.list.person.push({
      name: '',
      phone: '',
      address: '',
      primaryContact: 0,
      primaryDecision: 0,
      job: '',
      department: '',
      decision: '',
    });
  };

  const setPersonPrimaryContact = (e: number, rowIndex: number) => {
    if (e === 1)
      form.list.person.forEach((item: any, index: number) => {
        if (index !== rowIndex) item.primaryContact = 0;
      });
  };
  const setPersonPrimaryDecision = (e: number, rowIndex: number) => {
    if (e === 1)
      form.list.person.forEach((item: any, index: number) => {
        if (index !== rowIndex) item.primaryDecision = 0;
      });
  };

  const delPerson = (rowIndex: any) => {
    if (form.list.person.length === 1) return;
    form.list.person.splice(rowIndex, 1);
  };

  const rules = reactive({
    name: [{ required: true, message: '请输入客户名称' }],
    level: [{ required: true, message: '请选择客户级别' }],
    customerContactPhone: [{ required: true, validator: validatePhone }],
    customerEmail: [{ required: true, validator: validateEmail }],
    city: [{ required: true, message: '请输入省市区' }],
    address: [{ required: true, message: '请输入联系地址' }],
    sourceId: [{ required: true, message: '请选择客户来源' }],
    industry: [{ required: true, message: '请选择客户行业' }],
    salesId: [{ required: true, message: '请选择客户行业' }],
    customerType: [{ required: true, message: '请选择客户行业' }],
    contactName: [{ required: true, message: '请输入联系姓名' }],
    contactPhone: [{ required: true, validator: validatePhone }],
  });

  const formKey = Object.keys(form); // 储存form的key
  const enterpriseFormKey = Object.keys(enterpriseForm); // 储存enterpriseForm的key
  const fieldNames = { value: 'name', label: 'name' };
  // 获取对应客户详情信息
  const getClientDetail = async () => {
    try {
      const res = await GetClientDetailTabs({
        id,
        typeId: 1,
      });
      form.list = res;
      form.list.file = [];
      form.list.entry = [
        { name: '', phone: '', address: '', primaryContact: 1, remark: '' },
      ];
      form.list.person = [
        {
          name: '',
          phone: '',
          address: '',
          primaryContact: 1,
          primaryDecision: 1,
          job: '',
          department: '',
          decision: '',
        },
      ];
    } catch (error: unknown) {
      console.log(error);
    }
  };

  onMounted(() => {
    if (id) {
      getClientDetail();
    }
  });

  let isEdit = ref(false); // 判断用户是否点击编辑按钮
  const isEditBtn = () => {
    isEdit.value = !isEdit.value;
  };

  // 保存按钮
  const save = async () => {
    try {
      // enterpriseRef.value.currFormRef;

      // // 判断4个表单是否校验通过
      let [flag1, flag2, flag3, flag4] = [false, false, false, false];

      await enterpriseRef.value.currFormRef.validate((valid: any) => {
        if (valid === undefined) flag4 = true;
      });

      await formNameRef.value.validate((valid: any) => {
        if (valid === undefined) flag1 = true;
      });

      await formInfoRef.value.validate((valid: any) => {
        if (valid === undefined) flag2 = true;
      });

      await formRef.value.validate((valid: any) => {
        if (valid === undefined) flag3 = true;
      });

      // // 4个flag都为true才能执行post提交
      if (flag1 && flag2 && flag3 && flag4) {
        if (type.value === 'add' && route.query.id) {
          enterpriseForm.establishmentDate = Number(
            enterpriseForm.establishmentDate
          );
          enterpriseForm.approvalDate = Number(enterpriseForm.approvalDate);
          for (let i in enterpriseRef.value.currForm) {
            form.list[i] = enterpriseRef.value.currForm[i];
          }
          if (enterpriseRef.value.currForm.file.length) {
            form.list.file = form.list.file.concat([
              {
                name: enterpriseRef.value.currForm.file[0].name,
                addr: enterpriseRef.value.currForm.file[0].addr,
                fileType: 2,
              },
            ]);
          }
          form.list.isNeedPerfect = 2;
          await putClientDetail(form.list);
        } else {
          enterpriseForm.establishmentDate = Number(
            enterpriseForm.establishmentDate
          );
          enterpriseForm.approvalDate = Number(enterpriseForm.approvalDate);
          for (let i in enterpriseRef.value.currForm) {
            if (i === 'file') break;
            form.list[i] = enterpriseRef.value.currForm[i];
          }
          if (enterpriseRef.value.currForm.file.length) {
            form.list.file = form.list.file.concat([
              {
                name: enterpriseRef.value.currForm.file[0].name,
                addr: enterpriseRef.value.currForm.file[0].addr,
                fileType: 2,
              },
            ]);
          }
          if (form.list.entry.length) {
            if (!form.list.entry.some((e) => e.primaryContact === 1)) {
              Message.error('收货人必须有一名首要联系人！');
              return;
            }
          }
          await PostClientAdd(form.list);
        }
        router.back();
        // await PostClientAdd(form);
      }
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 获取客户设置信息
  const customerFrom = ref();
  const customerType = ref();
  const customerLevel = ref();
  const getClientSettingInfo = async () => {
    const res = await GetClientSettingInfo();
    customerFrom.value = res.customerFrom;
    customerType.value = res.customerType;
    customerLevel.value = res.customerLevel;
  };
  getClientSettingInfo();

  // 获取销售负责人信息
  const PersonnelInfoData = ref();
  const GetPersonnelInfo = async () => {
    const res = await GetPersonnelinformation({ page: 1, size: 99999 });
    PersonnelInfoData.value = res.content.data;
  };
  GetPersonnelInfo();
  // 取消按钮
  const cancel = () => {
    router.back();
  };
</script>

<style scoped lang="less">
  .client-add {
    .base-info {
      padding: 10px 40px 10px 40px;

      .avatar {
        position: absolute;
        width: 100px;
      }
      &-header {
        padding: 0 100px;
        :deep(.arco-form-item-content-flex) {
          display: block;
          line-height: 32px;
          color: #cccccc29;
        }
      }

      &-extra {
        .contact-info,
        .invoice-info,
        .client-info,
        .remarks-info {
          padding: 0 100px;
        }
      }
    }
  }

  .item {
    // width: 100px;
    // height: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 80px;
    height: 80px;
    margin-bottom: 0;
    color: var(--color-text-2);
    text-align: center;
    background: var(--color-fill-2);
    border: 1px dashed var(--color-neutral-3);
    border-radius: var(--border-radius-small);
    transition: all 0.1s cubic-bezier(0, 0, 1, 1);
  }

  :deep(.arco-image-footer-extra) {
    display: flex;
    justify-content: center;
    width: 100%;
    font-size: 12px;
    padding-bottom: 3px;
    padding: 0px;
  }

  .action {
    // padding: 5px 4px;
    font-size: 12px;
    // margin-left: 12px;
    border-radius: 2px;
    line-height: 1;
    cursor: pointer;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }

  .title-item {
    width: 100%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
    margin-top: 20px;
    margin-bottom: 20px;
  }

  // .base-info-extra:hover .contact-info {
  //   border: 1px solid red;
  //   border-radius: 5px;
  //   padding: 20px;
  // }
</style>
